package com.sharemarking.wa.platform.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.Page;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.eum.OrderStateEum;
import com.sharemarking.wa.common.exception.DriverException;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.common.entity.*;
import com.sharemarking.wa.common.eum.OrderOperateTypeEum;
import com.sharemarking.wa.platform.dto.orderDispatch.OrderInfoDto;
import com.sharemarking.wa.platform.dto.orderDriver.DeliveryInfo;
import com.sharemarking.wa.platform.dto.orderDriver.OrderDetailsDto;
import com.sharemarking.wa.platform.dto.orderDriver.OrderListDto;
import com.sharemarking.wa.platform.dto.orderDriver.OrgCarListDto;
import com.sharemarking.wa.platform.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sharemarking.wa.common.SysHttpStatus.REQUIRED_PARAMS_ERROR;
import static com.sharemarking.wa.common.SysHttpStatus.UN_DRIVER_VERIFY;

/**
 * @author dxy
 */
@Service
public class OrderDriverService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderManagementMapper orderManagementMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private OrgMemberMapper orgMemberMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderDriverMapper orderDriverMapper;
    @Autowired
    private DriverVerifyMapper driverVerifyMapper;
    @Autowired
    private OrgCarMapper orgCarMapper;
    @Autowired
    private JGPushService jgPushService;

    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> confirmOrder() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");
        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }

        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code));
        if (!order.getState().equals(OrderStateEum.DRIVER_CONFIRM.getKey())) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }

        order.setDriverId(memberId);
        order.setState(OrderStateEum.NO_TRANSPORT.getKey());
        order.setUpdateDate(new Date());


        orderMapper.update(order, new QueryWrapper<Order>().eq("code", code));

        Integer driverOrgId = orgMemberMapper.selectOne(
                new QueryWrapper<OrgMember>().select("org_id").eq("member_id",memberId)
        ).getOrgId();
        String messageStr = "您好，尾号为" + order.getCode().substring(order.getCode().length() - 10)
                + "的子订单已被" + orgMapper.getOrgNameById(driverOrgId) + "接单，废品装货地址" +
                orderDriverMapper.getLoadingAddressByOrderId(order.getId())
                + "，司机" + memberMapper.getRealNameById(memberId) + "，车牌" + order.getCarNumber() + "，预计抵达产废单位时间" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getArrivalTime());
        jgPushService.pushTag(messageStr,order.getSendOrgMemberId());
        jgPushService.pushTag(messageStr,order.getReceiveOrgMemberId());
        jgPushService.pushTag(messageStr,memberId);

        return ResponseParams.ok(null);
    }


    public ResponseParams<?> getCarList() throws Exception {
        Integer memberId = ss.getCurrentUserId();

        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        //判断是否认证
        DriverVerify driverVerify = driverVerifyMapper.selectOne(new QueryWrapper<DriverVerify>().select("org_id").eq("member_id", memberId).eq("exam_state", "1"));

        if (driverVerify == null) {
            throw DriverException.create(ResponseParams.error(UN_DRIVER_VERIFY));
        }

        //获取车辆列表
        List<OrgCar> orgCarList = orgCarMapper.selectList(new QueryWrapper<OrgCar>().eq("org_id", driverVerify.getOrgId()).last(" limit " + (pageIndex - 1) * pageSize + "," + pageSize));

        List<OrgCarListDto> orgCarListDtos = new ArrayList<>();
        //进行转换
        for (int i = 0; i < orgCarList.size(); i++) {
            OrgCarListDto o = new OrgCarListDto();
            BeanUtils.copyProperties(orgCarList.get(i), o);
            orgCarListDtos.add(o);
        }

        //查找总数
        Integer total = orgCarMapper.selectCount(new QueryWrapper<OrgCar>().eq("org_id", driverVerify.getOrgId()));

        return ResponseParams.ok(new Page<>(orgCarListDtos, pageIndex, pageSize, total, orgCarListDtos.size() == pageSize));
    }


    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> deliveryOrder() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");

        //查询order_id
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code).eq("driver_id", memberId));

        if (order == null || !order.getState().equals(OrderStateEum.NO_TRANSPORT.getKey())) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }

        List<DeliveryInfo> deliveryList = orderDriverMapper.getDeliveryList(code, memberId);
        for (DeliveryInfo delivery : deliveryList) {
            if (delivery.getRealWeight() == null) {
                throw RequestException.create(ResponseParams.isDataError("废品：" + delivery.getName() + " 还未送单"));
            }
        }

        //更改订单状态为运输中，并设置实际转运时间
        Order updateOrder = new Order();
        updateOrder.setId(order.getId());
        updateOrder.setState(OrderStateEum.TRANSPORTING.getKey());
        updateOrder.setActualTransferTime(new Date());
        orderDriverMapper.updateOrderState(updateOrder);

        String messageStr = "您好，尾号为" + order.getCode().substring(order.getCode().length() - 10) + "的子订单,废品正在送往"+orgMapper.getOrgNameById(order.getReceiveOrgId())+"，废品卸货地址是"+orderDriverMapper.getUnLoadingAddressByOrderId(order.getId());
        jgPushService.pushTag(messageStr,order.getSendOrgMemberId());
        jgPushService.pushTag(messageStr,order.getReceiveOrgMemberId());
        jgPushService.pushTag(messageStr,memberId);

        return ResponseParams.ok(null);
    }


    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> addOrEditDelivery() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");
        String wasteId = request.getParameter("wasteId");
        String pics = request.getParameter("pics");
        String realWeight = request.getParameter("realWeight");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }
        if (StringUtils.isEmpty(wasteId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("wasteId"));
        }

        //对图片链表进行处理
        String picsJoin;
        try {
            List<String> picsList = JSONArray.parseArray(pics, String.class);
            picsJoin = String.join(",", picsList);
        } catch (Exception e) {
            throw RequestException.create(ResponseParams.isDataError("pics格式错误"));
        }
        //获取该订单id
        Integer orderId = orderMapper.selectOne(new QueryWrapper<Order>().select("id").eq("code", code).eq("driver_id", memberId)).getId();
        if (orderDetailMapper.selectCount(new QueryWrapper<OrderDetails>().eq("order_id", orderId).eq("waste_id", wasteId)) == 0) {
            throw RequestException.create(ResponseParams.isDataError("wasteId错误"));
        }

        OrderDetails orderDetails = new OrderDetails();
        //设置order_id
        orderDetails.setOrderId(orderId);
        orderDetails.setPics(picsJoin);
        //设置常规字段
        orderDetails.setWasteId(Integer.valueOf(wasteId));
        orderDetails.setRealWeight(Double.valueOf(realWeight) * 100);
        orderDetails.setUpdateDate(new Date());
        //更新数据
        orderDriverMapper.updateOrderDetails(orderDetails);

        return ResponseParams.ok(null);
    }


    public ResponseParams<?> getDeliveryInfo() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");
        String wasteId = request.getParameter("wasteId");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }
        if (StringUtils.isEmpty(wasteId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("wasteId"));
        }


        DeliveryInfo deliveryInfo = orderDriverMapper.getDeliveryInfo(code, Integer.valueOf(wasteId), memberId);


        return ResponseParams.ok(deliveryInfo);
    }


    /*
     * 将时间戳转换为时间
     */
    public static Date getStringToDate(String time) throws Exception {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = format.parse(format.format(new Long(Long.parseLong(time))));
            return date;
        } catch (Exception e) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }
    }

//    public static void main(String[] args) {
//        try {
//            System.out.println( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getStringToDate("1591671926773")));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
